package top.yvyan.guettable.activity;

import static com.xuexiang.xui.XUI.getContext;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.button.ButtonView;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.picker.XSeekBar;

import java.util.List;

import top.yvyan.guettable.Gson.Semester;
import top.yvyan.guettable.R;
import top.yvyan.guettable.data.AccountData;
import top.yvyan.guettable.data.GeneralData;
import top.yvyan.guettable.data.MoreData;
import top.yvyan.guettable.data.ScheduleData;
import top.yvyan.guettable.data.TokenData;
import top.yvyan.guettable.service.fetch.StaticService;
import top.yvyan.guettable.util.DialogUtil;
import top.yvyan.guettable.util.ToastUtil;

public class SetTermActivity extends AppCompatActivity implements View.OnClickListener {
    public static int REQUEST_CODE = 14;
    public static int OK = 10;
    public static int OFF = 11;

    private TextView stuId;
    private TextView stuName;
    private Spinner spinnerTerm;
    private ButtonView input;

    private List<Semester> semesters;
    private GeneralData generalData;

    private MiniLoadingDialog mMiniLoadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_term);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        if (!AccountData.newInstance(this).getIsLogin()) {
            ToastUtil.showToast(getApplicationContext(), "您还未登录！");
            finish();
        } else {
            init();
        }
        Intent thisIntent = getIntent();
        //自动设置学期&星期
        boolean auto = thisIntent.getBooleanExtra("auto", false);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this);
        if (auto) {
            //存储日期模式为自动
            GeneralData.setAutoTerm(true);
            //请求/解析数据
            getDate();
        } else {
            initData();
        }
    }

    private void init() {
        stuId = findViewById(R.id.stu_id);
        stuName = findViewById(R.id.stu_name);
        spinnerTerm = findViewById(R.id.spinner_term);
        ButtonView back = findViewById(R.id.logoff);
        input = findViewById(R.id.input);
        back.setOnClickListener(this);
        input.setOnClickListener(this);
        generalData = GeneralData.newInstance(this);
        stuId.setText(generalData.getNumber());
        stuName.setText(generalData.getName());
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        ArrayAdapter<String> SemesterAdapter = new ArrayAdapter<>(this, R.layout.support_simple_spinner_dropdown_item);
        for (Semester semester : semesters) {
            SemesterAdapter.add(semester.nameZh);
        }
        spinnerTerm.setAdapter(SemesterAdapter);
        try {
            // 自动选择当前学期
            int idx = 0;
            Semester currentSemester = generalData.getSemester();
            if (currentSemester != null) {
                for (Semester semester : semesters) {
                    if (currentSemester.id == semester.id) {
                        spinnerTerm.setSelection(idx);
                        break;
                    }
                    idx++;
                }
            }
        } catch (Exception ignored) {
        }
        input.setClickable(true);
    }


    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.logoff:
                AccountData.newInstance(this).logoff();
                Intent intent = getIntent();
                setResult(OFF, intent);
                finish();
                break;
            case R.id.input:
                //显示loading
                input.setClickable(false);
                try {
                    int idx = spinnerTerm.getSelectedItemPosition();
                    if (idx >= this.semesters.size()) {
                        ToastUtil.showToast(this,"出现内部错误，请检查是否正确选择了学期");
                        break;
                    }
                    Semester semester = this.semesters.get(idx);
                    if (semester == null) {
                        ToastUtil.showToast(this,"出现内部错误，请检查是否正确选择了学期");
                        break;
                    }
                    generalData.setSemester(semester);
                    ScheduleData.deleteInputCourse();
                    if (!ScheduleData.getUserCourseBeans().isEmpty()) {
                        DialogUtil.IDialogService service = new DialogUtil.IDialogService() {
                            @Override
                            public void onClickYes() {
                                importCourse();
                            }

                            @Override
                            public void onClickBack() {
                                ScheduleData.deleteUserCourse();
                                importCourse();
                            }
                        };
                        DialogUtil.showDialog(this, "提示", false, "保留", "删除", "您修改了学期/账号，是否保留手动添加的课程？\r\n\r\nTip:若您只是临时切换，建议保留。", service);
                    } else {
                        importCourse();
                    }
                } catch (Exception ignore) {
                }
                break;
        }
    }

    private void initData() {
        //显示loading
        input.setClickable(false);
        mMiniLoadingDialog.updateMessage("正在从教务系统获取学期列表...");
        mMiniLoadingDialog.show();
        new Thread(() -> {
            getSemesterList();
            runOnUiThread(() -> {
                mMiniLoadingDialog.dismiss();
                initView();
            });
        }).start();
    }

    private void importCourse() {
        generalData.setLastUpdateTime(-1);
        GeneralData.setAutoTerm(false); //关闭自动学期
        ScheduleData.setUpdate(true);
        ToastUtil.showToast(getApplicationContext(), "正在导入课表，受教务系统影响，最长需要约10秒，请耐心等待，不要滑动页面");
        Intent intent = getIntent();
        setResult(OK, intent);
        finish();
    }

    /**
     * 在线获取学期信息
     */
    private void getDate() {
        new Thread(() -> {
            //显示loading
            runOnUiThread(() -> {
                input.setClickable(false);
                mMiniLoadingDialog.updateMessage("正在设置学期...");
                mMiniLoadingDialog.show();
            });
            //设置
            try {
                int n = setDate();
                if (n == 0) { //成功
                    runOnUiThread(() -> {
                        input.setClickable(true);
                        mMiniLoadingDialog.dismiss();
                        ToastUtil.showToast(getApplicationContext(), "正在导入课表，受教务系统影响，最长需要约10秒，请耐心等待，不要滑动页面");
                    });
                    //删除已有课程，重新导入
                    generalData.setLastUpdateTime(-1);
                    ScheduleData.deleteInputCourse();
                    ScheduleData.setUpdate(true);
                    Intent intent = getIntent();
                    setResult(OK, intent);
                    finish();
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            runOnUiThread(() -> {
                input.setClickable(true);
                mMiniLoadingDialog.dismiss();
            });
        }).start();
    }

    private int getSemesterList() {
        TokenData tokenData = TokenData.newInstance(this);
        boolean state = tokenData.tryUpdate(() -> {
            List<Semester> semesters = StaticService.getAllClassTableSemester(this, tokenData.getbkjwTestCookie());
            if (semesters == null) return false;
            this.semesters = semesters;
            MoreData.setSemesterList(semesters);
            return true;
        });
        if (!state) return -1;
        return 0;
    }

    /**
     * 独立出来的请求和解析学期的函数（需要在线程内执行）
     *
     * @return 0  成功
     * -1 失败
     */
    private int setDate() {
        TokenData tokenData = TokenData.newInstance(this);
        boolean state = tokenData.tryUpdate( () -> {
            List<Semester> semesters = StaticService.getAllClassTableSemester(this, tokenData.getbkjwTestCookie());
            if (semesters == null) return false;
            this.semesters = semesters;
            MoreData.setSemesterList(semesters);
            Semester semester = StaticService.getSemester(semesters);
            generalData.setSemester(semester);
            return true;
        });
        if (!state) return -1;
        return 0;
    }
}